import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/card_info_entity.dart';
import 'package:nyh_motorcade_app/entity/energy_type_entity.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';
import 'package:nyh_motorcade_app/widgets/custom_app_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nyh_motorcade_app/widgets/custom_popup_menu_item.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:nyh_motorcade_app/widgets/text_button_with_icon.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'card_manage_controller.dart';

class CardManagePage extends StatelessWidget {
  final controller = Get.put(CardManageController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CardManageController>(
      builder: (controller) {
        return Scaffold(
          backgroundColor: Colours.color_background,
          appBar: CustomAppBar(
            context: context,
            title: controller.isFormCardManage ? "卡管理" : "卡账户",
            actions: [buildActionsWidget()],
          ),
          body: Column(
            children: [
              buildHeaderWidget(),
              buildListWidget(),
            ],
          ),
        );
      },
    );
  }

  Widget buildActionsWidget() {
    return controller.isFormCardManage
        ? IconButton(
            onPressed: () {
              controller.goToActivateCardPage();
            },
            icon: Image.asset("images/ic_add_card.png"),
          )
        : Container();
  }

  Widget buildHeaderWidget() {
    return Container(
      padding: EdgeInsets.only(left: 8.w, right: 16.w),
      height: 40.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextButtonWithIcon(
                onPressed: () {
                  showEnergyTypeMenu();
                },
                icon: Image.asset(controller.showEnergyTypeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
                label: Text(
                  controller.energyTypeName.isNotEmpty ? controller.energyTypeName : "能源类型",
                  style: TextStyle(
                    color: Colours.color_text_theme,
                    fontSize: 14.sp,
                  ),
                ),
                textIconPadding: 5.w,
                iconTextAlignment: IconTextAlignment.iconRightTextLeft,
              ),
              SizedBox(
                width: 15.w,
              ),
              TextButtonWithIcon(
                onPressed: () {
                  showCardTypeMenu();
                },
                icon: Image.asset(controller.showCardTypeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
                label: Text(
                  controller.cardTypeName.isNotEmpty ? controller.cardTypeName : "卡归属",
                  style: TextStyle(
                    color: Colours.color_text_theme,
                    fontSize: 14.sp,
                  ),
                ),
                textIconPadding: 5.w,
                iconTextAlignment: IconTextAlignment.iconRightTextLeft,
              ),
            ],
          ),
          Text(
            "共${controller.cardCount}条",
            style: TextStyle(
              color: Colours.color_b7b7c0,
              fontSize: 14.sp,
            ),
          )
        ],
      ),
    );
  }

  Future<void> showEnergyTypeMenu() async {
    List<EnergyTypeEntity> list = await controller.getEnergyType();
    if (list.isEmpty) {
      return;
    }
    controller.showEnergyTypeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(16.w, ScreenUtil().statusBarHeight + 56 + 40.w, ScreenUtil().screenWidth, 0.w),
      items: controller.energyTypeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.energyTypeList[e].dictdataName ?? "")).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectEnergyType(value);
    });
  }

  void showCardTypeMenu() {
    if (controller.cardTypeList.isEmpty) {
      return;
    }
    controller.showCardTypeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(100.w, ScreenUtil().statusBarHeight + 56 + 40.w, ScreenUtil().screenWidth, 0.w),
      items: controller.cardTypeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.cardTypeList[e].name)).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectCardType(value);
    });
  }

  Widget buildListWidget() {
    return Expanded(
      child: MultiStateWidget(
        child: SmartRefresher(
          controller: controller.refreshController,
          enablePullDown: true,
          enablePullUp: true,
          onRefresh: controller.onRefresh,
          onLoading: controller.onLoading,
          child: ListView.builder(
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            controller: controller.scrollController,
            itemCount: controller.cardInfoList.length,
            itemBuilder: (context, index) {
              return buildItemWidget(index);
            },
          ),
        ),
        state: controller.multiState,
        onRetry: () {
          controller.onRetry();
        },
      ),
    );
  }

  Widget buildItemWidget(int index) {
    CardInfoItem entity = controller.cardInfoList[index];
    return Container(
      margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 12.w),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.w),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.w),
        child: Material(
          color: Colours.color_white,
          child: InkWell(
            onTap: () {
              controller.goToCardDetailsOrCardCashFlowPage(entity.id);
            },
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 13.w, horizontal: 16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          entity.name ?? "",
                          style: TextStyle(
                            color: Colours.color_text_theme,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      Visibility(
                        visible: (entity.cardType ?? "").isNotEmpty,
                        child: Container(
                          margin: EdgeInsets.only(left: 8.w),
                          padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                          decoration: BoxDecoration(
                            color: (entity.cardType ?? "") == Constant.OWN_CARD ? Colours.color_34c759 : Colours.color_theme,
                            borderRadius: BorderRadius.circular(5.w),
                            border: Border.all(
                              width: 1.w,
                              color: (entity.cardType ?? "") == Constant.OWN_CARD ? Colours.color_34c759 : Colours.color_theme,
                            ),
                          ),
                          child: Text(
                            entity.cardTypeName ?? "",
                            style: TextStyle(
                              color: Colours.color_white,
                              fontSize: 10.sp,
                            ),
                          ),
                        ),
                      ),
                      Visibility(
                        visible: (entity.energyTypeName ?? "").isNotEmpty,
                        child: Container(
                          margin: EdgeInsets.only(left: 8.w),
                          padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                          decoration: BoxDecoration(
                            color: Colours.color_white,
                            borderRadius: BorderRadius.circular(5.w),
                            border: Border.all(width: 1.w, color: Colours.color_6f7082),
                          ),
                          child: Text(
                            entity.energyTypeName ?? "",
                            style: TextStyle(
                              color: Colours.color_6f7082,
                              fontSize: 10.sp,
                            ),
                          ),
                        ),
                      ),
                      Visibility(
                        visible: entity.status == 0,
                        child: Container(
                          margin: EdgeInsets.only(left: 8.w),
                          padding: EdgeInsets.only(left: 5.w, right: 5.w, bottom: 1.w),
                          decoration: BoxDecoration(
                            color: Colours.color_cfcfd5,
                            borderRadius: BorderRadius.circular(5.w),
                            border: Border.all(width: 1.w, color: Colours.color_cfcfd5),
                          ),
                          child: Text(
                            "已禁用",
                            style: TextStyle(
                              color: Colours.color_white,
                              fontSize: 10.sp,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 5.w,
                  ),
                  Text(
                    entity.cardNumber ?? "",
                    style: TextStyle(
                      color: Colours.color_b7b7c0,
                      fontSize: 14.sp,
                    ),
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Baseline(
                            baseline: 30.w,
                            baselineType: TextBaseline.alphabetic,
                            child: Text(
                              "余额(元)：",
                              style: TextStyle(
                                color: Colours.color_6f7082,
                                fontSize: 12.sp,
                              ),
                            ),
                          ),
                          Baseline(
                            baseline: 30.w,
                            baselineType: TextBaseline.alphabetic,
                            child: Text(
                              FormatUtils.formatMoney(entity.cardBalance),
                              style: TextStyle(
                                color: Colours.color_6f7082,
                                fontSize: 14.sp,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Visibility(
                        visible: controller.permissionTransferCard,
                        child: TextButton(
                          onPressed: () {
                            controller.goToRapidTransferPage(entity.id, entity.name, entity.cardBalance);
                          },
                          child: Text(
                            "划拨",
                            style: TextStyle(
                              color: Colours.color_theme,
                              fontSize: 14.sp,
                            ),
                          ),
                          style: ButtonStyle(
                            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            minimumSize: MaterialStateProperty.all(Size(80.w, 30.w)),
                            padding: MaterialStateProperty.all(EdgeInsets.all(0)),
                            side: MaterialStateProperty.all(BorderSide(width: 1.w, color: Colours.color_theme)),
                            shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.w))),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
